﻿using System;
using System.Reflection;
using System.Text;
using Microsoft.Xrm.Sdk;
using XrmLibrary.Enums;
using XrmLibrary.Extensions;
using XrmLibrary.Context;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]
namespace XrmLibrary
{
    public sealed class Tracer 
    {
        private static readonly log4net.ILog _log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// Traces a variety of optional details to the trace log.
        /// </summary>
        /// <param name="fromMethod">The method to trace details regarding.</param>
        /// <param name="message">The message with optional format.</param>
        /// <param name="entity">The entity (optional).</param>
        /// <param name="exception">The exception (optional).</param>
        /// <param name="args">The args (optional) to use in message format.</param>
        public static void Trace(string fromMethod, string message, Entity entity = null, Exception exception = null, params object[] args)
        {
            if (_log.IsDebugEnabled)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLineFormat("Method: {0}", fromMethod);
                if(entity != null)
                {
                    String entityDetails = entity.GetDetails();
                    sb.AppendLineFormat("Entity: {0}", entityDetails);
                }
                if(exception != null)
                {
                    String exceptionDetails = exception.GetExceptionDetails();
                    sb.AppendLineFormat("Exception: {0}", exceptionDetails);
                }
                sb.AppendFormat("Message: {0}", String.Format(message, args));
                _log.Debug(sb.ToString());
            }
        }

        public static Boolean IsDebugEnabled
        {
            get { return _log.IsDebugEnabled; }
        }

        public static void Log(LogContext context)
        {
            switch (context.LogType)
            {
                case LogType.Debug:
                    _log.Debug(context.ToString());
                    break;
                case LogType.Success:
                case LogType.Info:
                    _log.Info(context.ToString());
                    break;
                case LogType.Warn:
                    _log.Warn(context.ToString());
                    break;
                case LogType.Error:
                    _log.Error(context.ToString());
                    break;
                case LogType.Fatal:
                    _log.Fatal(context.ToString());
                    break;
            }
        }
    }
}
